package com.kaizeli.website.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kaizeli.website.mapper.InvoiceMapper;
import com.kaizeli.website.pojo.entity.Invoice;
import com.kaizeli.website.pojo.dto.InvoiceDTO;
import com.kaizeli.website.response.Result;
import com.kaizeli.website.service.InvoiceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 开票单服务实现类
 */
@Service
public class InvoiceServiceImpl extends ServiceImpl<InvoiceMapper, Invoice> implements InvoiceService {

    @Autowired
    private InvoiceMapper invoiceMapper;
    
    @Autowired
    private JdbcTemplate jdbcTemplate;
    
    @Autowired(required = false)
    private com.kaizeli.website.service.PaymentService paymentService;

    @Override
    public Result<List<InvoiceDTO>> getInvoicesByAcceptanceId(Integer acceptanceId) {
        try {
            List<InvoiceDTO> invoices = invoiceMapper.selectByAcceptanceId(acceptanceId);
            return Result.success(invoices);
        } catch (Exception e) {
            return Result.error(500, "查询开票单失败：" + e.getMessage());
        }
    }

    @Override
    public Result<List<InvoiceDTO>> getInvoicesByProjectId(Long projectId) {
        try {
            List<InvoiceDTO> invoices = invoiceMapper.selectByProjectId(projectId);
            return Result.success(invoices);
        } catch (Exception e) {
            return Result.error(500, "查询开票单失败：" + e.getMessage());
        }
    }

    @Override
    public Result<List<InvoiceDTO>> getInvoicesByInvoiceStatus(String invoiceStatus) {
        try {
            List<InvoiceDTO> invoices = invoiceMapper.selectByInvoiceStatus(invoiceStatus);
            return Result.success(invoices);
        } catch (Exception e) {
            return Result.error(500, "查询开票单失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<Invoice> createInvoice(Invoice invoice) {
        try {
            // 设置默认值
            if (invoice.getInvoiceStatus() == null) {
                invoice.setInvoiceStatus("待开票");
            }
            
            invoice.setCreateTime(LocalDateTime.now());
            invoice.setUpdateTime(LocalDateTime.now());
            save(invoice);
            return Result.success(invoice);
        } catch (Exception e) {
            return Result.error(500, "创建开票单失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<Void> updateInvoice(Integer id, Invoice invoice) {
        try {
            invoice.setId(id);
            invoice.setUpdateTime(LocalDateTime.now());
            updateById(invoice);
            return Result.success();
        } catch (Exception e) {
            return Result.error(500, "更新开票单失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<Void> updateInvoiceStatus(Integer id, String invoiceStatus) {
        try {
            Invoice invoice = getById(id);
            if (invoice == null) {
                return Result.error(404, "开票单不存在");
            }
            
            int result = invoiceMapper.updateInvoiceStatus(id, invoiceStatus);
            if (result > 0) {
                // 如果开票状态更新为"已开票"，自动创建回款单
                if ("已开票".equals(invoiceStatus) && paymentService != null) {
                    try {
                        com.kaizeli.website.pojo.entity.Payment payment = new com.kaizeli.website.pojo.entity.Payment();
                        payment.setProjectId(invoice.getProjectId());
                        payment.setAmount(invoice.getInvoiceAmount());
                        payment.setPaymentDate(java.time.LocalDate.now());
                        payment.setPaymentStatus("待回款");
                        payment.setRemark("根据开票单自动创建");
                        paymentService.createPayment(payment);
                    } catch (Exception e) {
                        System.err.println("自动创建回款单失败: " + e.getMessage());
                    }
                }
                return Result.success();
            } else {
                return Result.error(500, "更新开票状态失败");
            }
        } catch (Exception e) {
            return Result.error(500, "更新开票状态失败：" + e.getMessage());
        }
    }

    @Override
    public Result<BigDecimal> calculateTotalInvoiceAmount(Long projectId) {
        try {
            BigDecimal totalInvoice = invoiceMapper.calculateTotalInvoiceAmount(projectId);
            return Result.success(totalInvoice);
        } catch (Exception e) {
            return Result.error(500, "计算总开票金额失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<Invoice> createInvoiceFromAcceptance(Integer acceptanceId) {
        try {
            // 查询验收单信息
            String sql = "SELECT id, acceptance_no, project_id, project_name, project_code, " +
                        "sub_project_name, contact_person, client, department, section, " +
                        "contract_no, acceptance_amount, status, acceptance_completion_time " +
                        "FROM project_acceptance WHERE id = ?";
            
            List<Map<String, Object>> list = jdbcTemplate.queryForList(sql, acceptanceId);
            
            if (list.isEmpty()) {
                return Result.error(404, "验收单不存在");
            }
            
            Map<String, Object> acceptance = list.get(0);
            
            // 创建开票单
            Invoice invoice = new Invoice();
            invoice.setAcceptanceId(acceptanceId);
            invoice.setProjectId(((Number) acceptance.get("project_id")).longValue());
            invoice.setProjectName((String) acceptance.get("project_name"));
            invoice.setProjectCode((String) acceptance.get("project_code"));
            invoice.setSubProjectName((String) acceptance.get("sub_project_name"));
            invoice.setContactPerson((String) acceptance.get("contact_person"));
            invoice.setClient((String) acceptance.get("client"));
            invoice.setDepartment((String) acceptance.get("department"));
            invoice.setSection((String) acceptance.get("section"));
            invoice.setContractNo((String) acceptance.get("contract_no"));
            
            // 设置开票金额（使用验收金额）
            BigDecimal acceptanceAmount = (BigDecimal) acceptance.get("acceptance_amount");
            if (acceptanceAmount != null) {
                invoice.setInvoiceAmount(acceptanceAmount);
                invoice.setTotalAmount(acceptanceAmount);
            } else {
                invoice.setInvoiceAmount(BigDecimal.ZERO);
                invoice.setTotalAmount(BigDecimal.ZERO);
            }
            
            // 生成开票单编号
            String invoiceNo = "INV" + System.currentTimeMillis();
            invoice.setInvoiceNo(invoiceNo);
            
            // 设置开票日期为验收完成时间
            LocalDateTime completionTime = (LocalDateTime) acceptance.get("acceptance_completion_time");
            if (completionTime != null) {
                invoice.setInvoiceDate(completionTime.toLocalDate());
            } else {
                invoice.setInvoiceDate(java.time.LocalDate.now());
            }
            
            invoice.setInvoiceStatus("待开票");
            invoice.setInvoiceType("增值税专用发票");
            invoice.setTaxRate(BigDecimal.ZERO);
            invoice.setTaxAmount(BigDecimal.ZERO);
            invoice.setCreateTime(LocalDateTime.now());
            invoice.setUpdateTime(LocalDateTime.now());
            
            save(invoice);
            return Result.success(invoice);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(500, "根据验收单创建开票单失败：" + e.getMessage());
        }
    }

    @Override
    public Result<InvoiceDTO> getInvoiceById(Integer id) {
        try {
            Invoice invoice = getById(id);
            if (invoice == null) {
                return Result.error(404, "开票单不存在");
            }
            
            // 转换为DTO
            InvoiceDTO invoiceDTO = new InvoiceDTO();
            invoiceDTO.setId(invoice.getId());
            invoiceDTO.setInvoiceNo(invoice.getInvoiceNo());
            invoiceDTO.setAcceptanceId(invoice.getAcceptanceId());
            invoiceDTO.setProjectId(invoice.getProjectId());
            invoiceDTO.setProjectName(invoice.getProjectName());
            invoiceDTO.setProjectCode(invoice.getProjectCode());
            invoiceDTO.setSubProjectName(invoice.getSubProjectName());
            invoiceDTO.setContactPerson(invoice.getContactPerson());
            invoiceDTO.setClient(invoice.getClient());
            invoiceDTO.setDepartment(invoice.getDepartment());
            invoiceDTO.setSection(invoice.getSection());
            invoiceDTO.setContractNo(invoice.getContractNo());
            invoiceDTO.setInvoiceDate(invoice.getInvoiceDate());
            invoiceDTO.setInvoiceAmount(invoice.getInvoiceAmount());
            invoiceDTO.setInvoiceType(invoice.getInvoiceType());
            invoiceDTO.setTaxRate(invoice.getTaxRate());
            invoiceDTO.setTaxAmount(invoice.getTaxAmount());
            invoiceDTO.setTotalAmount(invoice.getTotalAmount());
            invoiceDTO.setInvoiceStatus(invoice.getInvoiceStatus());
            invoiceDTO.setInvoicePersonId(invoice.getInvoicePersonId());
            invoiceDTO.setInvoicePersonName(invoice.getInvoicePersonName());
            invoiceDTO.setAttachmentUrls(invoice.getAttachmentUrls());
            invoiceDTO.setRemark(invoice.getRemark());
            
            return Result.success(invoiceDTO);
        } catch (Exception e) {
            return Result.error(500, "查询开票单失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<Void> deleteInvoice(Integer id) {
        try {
            Invoice invoice = getById(id);
            if (invoice == null) {
                return Result.error(404, "开票单不存在");
            }
            
            boolean result = removeById(id);
            if (result) {
                return Result.success();
            } else {
                return Result.error(500, "删除开票单失败");
            }
        } catch (Exception e) {
            return Result.error(500, "删除开票单失败：" + e.getMessage());
        }
    }
}

